package com.updesignsz.api.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.updesignsz.api.mapper.NewsMapper;
import com.updesignsz.commom.entity.News;
import com.updesignsz.commom.entity.Projects;
import com.updesignsz.commom.util.PageRequest;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 新闻
 * Creation date 2020-8-8 14:56:13
 */
@Service
public class NewsService {

    @Autowired
    private NewsMapper newsMapper;

    public PageInfo<News> findByPage(PageRequest pageRequest) {
        PageHelper.startPage(pageRequest.getPageNumber(), pageRequest.getPageSize());
        List<News> list = newsMapper.listPageAll(pageRequest.getFilters());
        return new PageInfo<>(list);
    }


    public News getById(Integer id) {
        return newsMapper.getById(id);
    }


    public Map<String, Object> getFrontOrAfterID(JSONObject json) {
        if (json.containsKey("id")) {
            News news = getById(json.optInt("id"));
            json.remove("id");
//            json.put("type", news.getType());
            List<News> list = newsMapper.listPageAll(json);
            Map<String, Object> data = new HashMap<>();
            for (int i = 0; i < list.size(); i++) {
                News entity = list.get(i);
                if (entity.getId().intValue() == news.getId().intValue()) {
                    Integer frontNumber = i == 0 ? -1 : i - 1;
                    Integer afterNumber = list.size() == (i + 1) ?  -1 : i + 1;
                    data.put("prev", frontNumber != -1 ?  list.get(frontNumber) : null);
                    data.put("curr", news);
                    data.put("next", afterNumber != -1 ?  list.get(afterNumber) : null);
                }
            }
            return data;
        } else {
            return null;
        }
    }
}